'use strict';

angular.module('mainApp')
  .service('treasureService', ['$http', function ($http) {
	  
	  this.searchTreasureTemplates = function(text, onSuccess, onFailure, onError) {
		  // ajax call service for treasures
		  this.handleHttpRequest('rest/treasureTemplates/search/' + text, HttpRequestType.Get, null, onSuccess, onFailure, onError);
	  };
	  
	  
	  this.createNewTreasureTemplate = function(treasureTemplateName, onSuccess, onFailure, onError){		  
		  this.handleHttpRequest('rest/treasureTemplates/new/' + treasureTemplateName, HttpRequestType.Put, null, onSuccess, onFailure, onError);		  
	  };
	  
	  
	  this.updateTreasureTemplate = function(treasureTemplate, onSuccess, onFailure, onError){	  
		  this.handleHttpRequest('rest/treasureTemplates/update/' + treasureTemplate.internalId, HttpRequestType.Post, treasureTemplate, onSuccess, onFailure, onError);	  
	  };
	  
	  
	  
	  // move this out to a util
	  this.handleHttpRequest = function(url, httpRequestType, data, onSuccess, onFailure, onError){
		  
		  var success = function(data){
			  if(data.objectType == "Error"){
				  onFailure("We need to pass error messages");
			  }
			  else{
				  onSuccess(data); 
			  }
		  };
		  
		  var error = function(data, status, headers, config){
			  onError(status, "Server Communication Error");
		  };
		  
		  if(httpRequestType == HttpRequestType.Put){
			  if(data){
				  $http.put(url, data).success(success).error(error);  
			  }
			  else{
				  $http.put(url).success(success).error(error);
			  }
		  }
		  else if(httpRequestType == HttpRequestType.Post){
			  if(data){
				  $http.post(url, data).success(success).error(error);
			  }
			  else{
				  $http.post(url).success(success).error(error);
			  }
		  }
		  else if(httpRequestType == HttpRequestType.Get){
			  $http.get(url).success(success).error(error);
		  }
		  else{
			  // unsupported request type
		  }
	  };
	  
       
  }]);